//
//  MallEditAddressViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/4.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallEditAddressViewController.h"
#import "YJLocationPicker.h"
#import "NSString+Common.h"
#import "CZHAddressPickerView.h"

@interface MallEditAddressViewController () <UITextFieldDelegate>

@property (strong, nonatomic) NSString *province;
@property (strong, nonatomic) NSString *city;
@property (strong, nonatomic) NSString *area;

@end

@implementation MallEditAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createUI];
    
}


- (void)createUI {
    
    NSArray *model;
    if (self.type) {
        self.navigationItem.title = @"修改地址";
        model = @[self.model.name, self.model.mobile, [NSString stringWithFormat:@"%@%@%@", self.model.province, self.model.city, self.model.district], self.model.detail];
    }
    else
        self.navigationItem.title = @"添加地址";
    
    self.view.backgroundColor = UISeparatedColorRGB;
    CGSize size = [LZCTools textSizeWithText:@"测试字数" font:kUHSystemFontWithSize(14)];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 4*(30+size.height))];
    [self.view addSubview:bgView];
    bgView.backgroundColor = kWhiteColor;
    
    NSArray *arr = [NSArray arrayWithObjects:@"收货人", @"手机号码", @"所在地区", @"详细地址", nil];
    
    for (int i = 0; i < arr.count; i++) {
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, (30+size.height)*i, size.width, 30+size.height)];
        [self.view addSubview:label];
        label.textColor = kGrayColor;
        label.text = arr[i];
        label.font = kUHSystemFontWithSize(14);
        
        UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, 15+(30+size.height)*i, SCREEN_WIDTH-(50+size.width), size.height)];
        [self.view addSubview:field];
        field.delegate = self;
        field.textColor = kGrayColor;
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        field.font = kUHSystemFontWithSize(14);
        
        if (self.type) {
            field.text = model[i];
        }
        
        if (i == 1) {
//            field.keyboardType = UIKeyboardTypeNumberPad;
        }
        else if (i == 2) {
            field.textAlignment = NSTextAlignmentRight;
            field.rightViewMode = UITextFieldViewModeAlways;
            UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
            field.rightView = imgV;
            imgV.image = IMAGE(@"arrow_right_grey");
            
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(field.x, field.y, field.width, field.height)];
            [self.view addSubview:view];
            [view addActionWithblock:^{
                NSLog(@"选择城市");
				
				[CZHAddressPickerView areaPickerViewWithAreaBlock:^(NSString *province, NSString *city, NSString *area) {
					field.text = [NSString stringWithFormat:@"%@%@%@", province, city, area];
					self.province = province;
					self.city = city;
					self.area = area;
				}];

            }];
        }
        
        field.tag = 1+i;
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, label.y+label.height-1, SCREEN_WIDTH, 1)];
        [self.view addSubview:line];
        line.backgroundColor = UISeparatedColorRGB;
        
    }
    
    UIButton *completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:completeBtn];
    [completeBtn setTitle:@"保存" forState:UIControlStateNormal];
    [completeBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    CGFloat btnHeight = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+SW(20);
    completeBtn.frame = CGRectMake(20, bgView.height+30, SCREEN_WIDTH-40, btnHeight);
    completeBtn.backgroundColor = UIMainColorRGB;
    completeBtn.layer.cornerRadius = 5;
    completeBtn.layer.masksToBounds = YES;
    [completeBtn addTarget:self action:@selector(completeClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark ===========代理方法==========
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

#pragma mark ===========响应方法==========
- (void)completeClick:(id)sender {
    NSLog(@"点击保存新地址");
    
    UITextField *t1 = [self.view viewWithTag:1];
    UITextField *t2 = [self.view viewWithTag:2];
    UITextField *t4 = [self.view viewWithTag:4];
    
    NSArray *arr = @[t1.text, t2.text, self.area, t4.text];
    NSArray *arrText = @[@"收货人不可以为空", @"手机号不可以为空", @"所在地区不可以为空", @"详细地址不可以为空"];
    for (int i = 0; i < arr.count; i++) {
        // 手机号不为空
        if ([NSString isEmpty:arr[i]]) {
            [self presentViewController:[LZCTools alertMessage:arrText[i]] animated:YES completion:nil];
            return;
        }
    }
    
    // 手机号码输入验证
    if (![NSString isValidatePhoneNumber:t2.text]) {
        [self presentViewController:[LZCTools alertMessage:@"您输入的不是手机号"] animated:YES completion:nil];
        return;
    }
    
    // POST /users/receive-addresses 添加收货地址，每人最多10个收货地址 province *省份 city *城市 district *地区 detail *详细地址 name *收货人姓名 mobile *收货人电话 is_default 是否设为默认 1是 0否（默认）
//#define APIReceiveAddresses            [APIUser stringByAppendingString:@"/receive-addresses"]

    NSDictionary *param = @{@"name":t1.text,
                            @"mobile":t2.text,
                            @"province":self.province,
                            @"city":self.city,
                            @"district":self.area,
                            @"detail":t4.text
                            };
    
    if (self.type) {
        NSString *url = [NSString stringWithFormat:@"%@/%ld", APIReceiveAddresses, self.model.addr_id];
        [[NetworkTool sharedTool] requestWithName:@"修改收货地址" URLString:url parameters:param method:@"PUT" callBack:^(id responseObject) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    else {
        [[NetworkTool sharedTool] requestWithName:@"添加收货地址" URLString:APIReceiveAddresses parameters:param method:@"POST" callBack:^(id responseObject) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
